package rexsee.core.browser;

import rexsee.core.browser.clazz.JavascriptInterface;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Handler;

public class RexseeGarbageCollector implements JavascriptInterface {

	public static final String INTERFACE_NAME = "GarbageCollector";
	@Override
	public String getInterfaceName() {
		return mBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return this;
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return this;
	}

	private final Context mContext;
	private final Browser mBrowser;

	private int mCycle = 2000;
	private final Handler mHandler = new Handler();
	private final Runnable mCollector = new Runnable() {
		@Override
		public void run() {
			if (mCycle <= 0) return;
			try {
				System.gc();
				mHandler.postDelayed(mCollector, mCycle);
			} catch (Exception e) {
			}
		}
	};

	public RexseeGarbageCollector(Browser browser) {
		super();
		mBrowser = browser;
		mContext = browser.getContext();
	}

	//JavaScript Interface
	public String getMemoryInfo() {
		ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
		((ActivityManager) mContext.getSystemService(Activity.ACTIVITY_SERVICE)).getMemoryInfo(mi);
		String rtn = "{";
		rtn += "\"available\":" + mi.availMem + ",";
		rtn += "\"threshold\":" + mi.threshold + ",";
		rtn += "\"lowMemory\":" + String.valueOf(mi.lowMemory);
		rtn += "}";
		return rtn;
	}
	public void freeMemory() {
		System.gc();
	}
	public void setAutoCollectorCycle(int milliseconds) {
		mCycle = milliseconds;
	}
	public int getAutoCollectorCycle() {
		return mCycle;
	}
	public void startAutoCollector() {
		mCollector.run();
	}
	public void stopAutoCollector() {
		mCycle = 0;
	}

}
